package android.twitter.clientroid;

import android.app.ListActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

public class SearchResultsActivity extends ListActivity
{
	private TwitterListAdapter adapter;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.searchresults);
		
		if(Globals.tweets.size() > 0)
		{
			adapter = new TwitterListAdapter(this, Globals.tweets);
			setListAdapter(adapter);
		}
		
		else
		{
			Toast.makeText(SearchResultsActivity.this, "Operation on empty result set !", Toast.LENGTH_LONG).show();
			
		}
		
	}
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
    	MenuInflater menuInflater=getMenuInflater();
    	menuInflater.inflate(R.menu.main_menu, menu);
    	return super.onCreateOptionsMenu(menu);
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
    	switch(item.getItemId())
    	{
	    	case R.id.menu_item_timeline:
				timeline();
				break;
    		case R.id.menu_item_tweet:
    			tweet();
    			break;
    		case R.id.menu_item_search:
    			search();
    			break;
    		case R.id.menu_item_logout:
    			logout();
    			break;
    	}
    	return super.onOptionsItemSelected(item);
    }
    
    private void timeline()
    {
    	Intent backIntent = new Intent(SearchResultsActivity.this, TimeLineActivity.class);
		startActivity(backIntent);
    }
    
    private void tweet()
    {
    	Intent tweetIntent = new Intent(SearchResultsActivity.this, SendTweetActivity.class);
		startActivity(tweetIntent);
    }
    
    private void search()
    {
    	Intent searchIntent = new Intent(SearchResultsActivity.this, SearchActivity.class);
		startActivity(searchIntent);
    }
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if ((keyCode == KeyEvent.KEYCODE_BACK))
        {
        	finish();
        }
        return super.onKeyDown(keyCode, event);
    }
    
    public void logout()
    {
    	SharedPreferences settings = getSharedPreferences(Constants.PREFS_NAME, MODE_PRIVATE);
		SharedPreferences.Editor editor = settings.edit();
		editor.remove("accessTokenToken");
		editor.remove("accessTokenSecret");
		editor.commit();
		Toast.makeText(SearchResultsActivity.this, "Application access is revoked", Toast.LENGTH_LONG).show();
		Intent backIntent = new Intent(SearchResultsActivity.this, LoginActivity.class);
		startActivity(backIntent);
    }

}